using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;

using MvcCms.Data;
using MvcCms.Data.Entities;
using MvcCms.Service.Entities;
using MvcCms.Service;
using MvcCms.Service.Validation;
using MvcCms.Web.Code;
using MvcCms.Web.ViewModels;
using MvcCms.Service.Cache;
using MvcCms.Service.Logging;
using Microsoft.Practices.ServiceLocation;
using System.IO;
using MvcCms.Service.Code.Email;

namespace MvcCms.Web.Controllers
{
    public class HomeAjaxController  : MvcCms.Service.Code.BaseClasses.MvcCmsControllerBase
    {
        #region Constructors

        private readonly IAccountService _accountService;
        private readonly ICmsService _cmsService;
        private readonly IMiscService _miscService;
        private readonly ISearchService _searchService;
        private readonly ICacheService _cacheService;
        private readonly IPortalService _portalService;
        public HomeAjaxController(ICmsService cmsService, IMiscService miscService, IAccountService accountService, ISearchService searchService, ICacheService cacheService, IPortalService portalService)
        {
            _cmsService = cmsService;
            _accountService = accountService;
            _searchService = searchService;
            _miscService = miscService;
            _cacheService = cacheService;
            _portalService = portalService;


        }

        #endregion

        public JsonResult Search(string data)
        {
            try
            {
                var currentPortal = _cacheService.GetCurrentPortal();
                bool usefulltext = currentPortal.UseFullText;
                var searchreq = new JavaScriptSerializer().Deserialize<SearchRequest>(data);
                string term = searchreq.Term;
                IEnumerable<DTOSearchResult> results = _searchService.Search(term, usefulltext);
                return Json(results);
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(ex.Message, ex);
                return Json(new { error = ex.Message });
            }
        }

        public JsonResult GetModules(int? pageId)
        {
            try
            {
                if (!pageId.HasValue) { return null; }
                IEnumerable<DTOModule> modules = _cmsService.ListModulesForPage(pageId.GetValueOrDefault());
                return Json(modules);
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(ex.Message, ex);
                return Json(new { error = ex.Message });
            }
        }

        public JsonResult GetWeightedModuleContent(string targetDiv)
        {
            try
            {
                var lastWeightedModuleId = 0;
                if (Session["LastWeightedModuleID"] != null)
                {
                    lastWeightedModuleId = int.Parse(Session["LastWeightedModuleID"].ToString());
                }
                string[] roles = new string[0];
                var user = _accountService.GetUser();
                if (user != null)
                {
                    roles = Roles.GetRolesForUser();
                }
                var weightedContentToSend = _cmsService.GetNextWeightedModuleForTargetDiv(targetDiv, Request.IsAuthenticated, roles, lastWeightedModuleId);
                if (weightedContentToSend != null)
                {
                    Session["LastWeightedModuleID"] = weightedContentToSend.ModuleID;
                    return Json(new
                    {
                        html = weightedContentToSend.Module.HTML,
                        transitionShowEffect = weightedContentToSend.TransitionShowEffect,
                        transitionHideEffect = weightedContentToSend.TransitionHideEffect,
                        hideDuration = weightedContentToSend.HideDuration,
                        showDuration = weightedContentToSend.ShowDuration,
                        ContainerClasses = weightedContentToSend.WeightedContent.ContainerClasses
                    });
                }
                else
                {
                    Session["LastWeightedModuleID"] = 0;
                    return Json(new { message = "No Module Could Be Found" });
                }
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(ex.Message, ex);
                return Json(new { error = ex.Message });
            }
        }

        public JsonResult RssReader(string data)
        {
            try
            {
                var rssreq = new JavaScriptSerializer().Deserialize<RssRequest>(data);
                IEnumerable<DTORSSItem> rssitems = _miscService.GetRssItems(rssreq.Rssurl);
                return Json(rssitems);
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(ex.Message, ex);
                return Json(new { error = ex.Message });
            }
        }

        public JsonResult FeedBack(string data)
        {
            try
            {
                var newFeedBackItem = new JavaScriptSerializer().Deserialize<FeedbackRequest>(data);
                var feedbackToCreate = new FeedBackItem
                {
                    Body = newFeedBackItem.Body,
                    Subject = newFeedBackItem.Subject + " from: " + newFeedBackItem.From
                };
                var portalService = ServiceLocator.Current.GetInstance<IPortalService>();
                portalService.CreateFeedBackItem(feedbackToCreate);

                MvcCmsEmails.DynamicEmail(newFeedBackItem.Subject, _cacheService.GetCurrentPortal().AdminEmail, newFeedBackItem.To, newFeedBackItem.Body + " from: " + newFeedBackItem.From);

                return Json(new { results = "Success" });
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(ex.Message, ex);
                return Json(new { error = ex.Message });
            }
        }

        [Authorize(Roles = "User")]
        public JsonResult PostCommentReply(string data, int pageId)
        {
            try
            {
                var newcommentReply = new JavaScriptSerializer().Deserialize<ContentComment>(data);

                ContentComment parentcomment = _cmsService.GetContentComment(newcommentReply.CommentID);
                newcommentReply.ParentComment = parentcomment;

                User commentuser = _accountService.GetUser();

                if (commentuser == null)
                {
                    commentuser = _accountService.GetUser("anonymous");
                }

                newcommentReply.AddedByAnonEmail = "";
                newcommentReply.AddedByAnonName = "";

                newcommentReply.User = commentuser;
                ContentPage commentpage = _cmsService.GetContentPage(pageId);
                newcommentReply.ContentPage = commentpage;

                newcommentReply.AddedDate = DateTime.Now;
                newcommentReply.AddedByIP = Request.UserHostAddress;
                newcommentReply.Approved = true;

                _cmsService.CreateContentComment(newcommentReply);
                MvcCmsEmails.CommentReply(newcommentReply);
                IEnumerable<DTOComment> comments = _cmsService.ListContentComments(newcommentReply.ContentPage.ContentPageID);


                return Json(comments);
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(ex.Message, ex);
                return Json(new { error = ex.Message });
            }
        }

        [ValidateInput(false)]
        [Authorize(Roles = "Editor")]
        public JsonResult UpdateComment(string data)
        {
            try
            {
                var commentToEdit = new JavaScriptSerializer().Deserialize<ContentComment>(data);

                ContentComment origcomment = _cmsService.GetContentComment(commentToEdit.CommentID);

                int pageid = origcomment.ContentPage.ContentPageID;

                origcomment.Body = commentToEdit.Body;
                origcomment.AddedByAnonEmail = commentToEdit.AddedByAnonEmail;
                origcomment.AddedByAnonName = commentToEdit.AddedByAnonName;
                origcomment.Approved = commentToEdit.Approved;
                if (origcomment.Approved)
                {
                    _cmsService.EditContentComment(origcomment);
                }
                else
                {
                    _cmsService.DeleteContentComment(origcomment);
                }
                IEnumerable<DTOComment> comments = _cmsService.ListContentComments(pageid);
                return Json(comments);
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(ex.Message, ex);
                return Json(new { error = ex.Message });
            }
        }

        public JsonResult GetContentComments(int? pageId)
        {
            if (!pageId.HasValue) { return null; }
            try
            {
                IEnumerable<DTOComment> comments = _cmsService.ListContentComments(pageId.GetValueOrDefault());
                return Json(comments);
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(ex.Message, ex);
                return Json(new { error = ex.Message });
            }
        }

        public JsonResult CreateContentComment(string data, int pageId)
        {
            try
            {
                var contentcommentToCreate = new JavaScriptSerializer().Deserialize<ContentComment>(data);
                if (contentcommentToCreate.Body.Trim().Length > 0)
                {
                    User commentuser = _accountService.GetUser();
                    if (commentuser!=null)
                    {
                        contentcommentToCreate.AddedByAnonEmail = "";
                        contentcommentToCreate.AddedByAnonName = "";
                    }
                    else
                    {
                        var user = _accountService.GetUser("anonymous");
                        commentuser = user;
                    }

                    contentcommentToCreate.User = commentuser;
                    ContentPage commentpage = _cmsService.GetContentPage(pageId);
                    contentcommentToCreate.ContentPage = commentpage;

                    contentcommentToCreate.AddedDate = DateTime.Now;
                    contentcommentToCreate.AddedByIP = Request.UserHostAddress;
                    contentcommentToCreate.Approved = true;
                    _cmsService.CreateContentComment(contentcommentToCreate);

                    IEnumerable<DTOComment> comments = _cmsService.ListContentComments(contentcommentToCreate.ContentPage.ContentPageID);
                    return Json(comments);
                }
                else
                {
                    return Json(new { error = "body required" });
                }
            }
            catch (Exception ex)
            {
                AppLogging.GetLogger().Error(ex.Message, ex);
                return Json(new { error = ex.Message });
            }
        }
    }
}